import { observable, action } from 'mobx';
import { Tools, Toast } from 'weaver-mobile';
import { ListViewPage } from 'weaver-mobile-page';
import { getFrameParams } from '../utils/utils';

function loop() { }

class MessagePageStore {
  @observable list = new ListViewPage.Store();
  @observable tabData = [];
  @observable tabFlag = '0';
  @observable bizstate = '';
  @observable tabSelectedKey = '';
  @observable refreshing = false;
  @observable loading = false;
  @observable needScroll = true;
  @observable needRefresh = false;
  @observable isInitMessagePage = true;
  @observable messagePageIndex = 0;
  @observable oldScrollHeight = 0;
  @observable hasNoMore = false;
  @observable scrollInTop = false;

  // pullToRefresh need render one more time to get ref
  @observable timer = null;
  @observable hasRenderOneMoreTime = false;

  @action
  updateRead = () => {
    const urlParams = getFrameParams();
    Tools.callApi({
      method: 'GET',
      url: '/api/msgcenter/homepage/setMsgRead',
      params: {
        id: urlParams.typeId
      },
    })
  }

  @action
  getMsgTypeTabs = () => {
    const urlParams = getFrameParams();

    return Tools.callApi({
      method: "GET",
      url: "/api/msgcenter/homepage/GetMsgTypeTabs",
      params: {
        typeId: urlParams['typeId'] ? urlParams['typeId'] : ''
      }
    }).then((res) => {
      if (res.datas && res.datas.length){
        let datas = JSON.parse(
          JSON.stringify(res.datas)
          .replace(/id/g, "viewcondition")
          .replace(/tabName/g, "title")
        );
        this.tabData = datas;
        this.tabFlag = '1';
        this.tabSelectedKey = datas[0].viewcondition;
        this.bizstate = datas[0].msgStateId;
      }
    })
  }

  @action
  getMessageData = (params, needRefresh, needScroll = true, cb = loop) => {
    needRefresh && (this.refreshing = true);
    needRefresh && (this.needRefresh = true);
    !needRefresh && (this.needRefresh = false);
    params.bizstate = this.bizstate;

    if (!this.isInitMessagePage) {
      this.loading = true
    }

    const urlParams = getFrameParams();
    if (urlParams['typeId']) {
      params.typeId = urlParams['typeId'];
    }

    params.selectState = '';
    if(this.tabData.length && params.bizstate){
      const filterSelect = this.tabData.filter(item => item.msgStateId === params.bizstate)

      params.selectState = filterSelect[0] ? filterSelect[0].selectState : ''
    }

    try {
      return Tools.callApi({
        method: 'POST',
        url: '/api/msgcenter/homepage/getMsgList',
        params,
      }).then(action((res) => {
        if (this.isInitMessagePage && res.data && res.data.length === 0) {
          if (this.tabFlag === "1") {
            let allKeyArr = [];
            let allIndexArr = [];

            this.tabData.forEach((item,index) => {
              if (!item.msgStateId) {
                allKeyArr.push(item.viewcondition);
                allIndexArr.push(index);
              }
            })

            this.bizstate =  allKeyArr.length ? '' : this.tabData[0].msgStateId;
            this.tabSelectedKey = allKeyArr[0] || this.tabData[0].viewcondition;
            this.messagePageIndex = allIndexArr[0] || 0;
            this.getMessageData(params, true, needScroll, cb)
          };
        }

        this.loading = false;
        const data = res.data
        const newState = {
          loading: false,
          current: params.current || 1,
          data: [ ...res.data , ...(params.current === 1 ? [] : this.list.data)],
          rowKey: 'messageid',
          isTable: false,
          template: { default: [] },
          typeId: res.typeId,
          mintime: res.mintime,
          msgid: res.msgid,
        };

        if (res.data.length > 0) {
          this.oldScrollHeight = res.data.length * 190;
        }
        this.hasNoMore = (data.length < 10);
        this.hasRenderOneMoreTime = (data.length < 10);
        this.list.setState(newState);
        this.list.updateDataSource();
        this.renderOneMoreTime();
        this.isInitMessagePage = false;
        needRefresh && (this.refreshing = false);
        needScroll && (this.needScroll = true);
        cb();
      }))
    } catch (e) {
      cb();
      Toast.info(e, 1);
    }
  }

  // pullToRefresh need render one more time to get ref
  @action
  renderOneMoreTime = () => {
    if (!this.hasRenderOneMoreTime) {
      this.timer = setTimeout(() => {
        this.list.updateDataSource();
        if (this.timer) {
          clearTimeout(this.timer);
          this.timer = null;
          this.hasRenderOneMoreTime = true;
        }
      }, 100);
    }
  }

  @action
  updateScroll(oldScrollHeight, needRefresh) {
    const doms = document.getElementsByClassName('wm-list-view-page-modal-scrollview')
    if (doms.length > 0) {
      if (needRefresh) {
        doms[0].scrollTop = doms[0].scrollHeight
      } else {
        doms[0].scrollTop = doms[0].scrollHeight - oldScrollHeight;
      }
    }
  }

  @action
  setNeedScroll = (needScroll) => {
    this.needScroll = needScroll;
  }

  @action
  setState = (params = {}) => {
    Object.keys(params).forEach((key) => {
      this[key] = params[key];
    });
  }
}

export default new MessagePageStore();